package com.smsc.headend.connector.netty.handler;

import com.smsc.headend.connector.service.LogTerminalAccessService;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.springframework.beans.factory.annotation.Autowired;

public class BytesOutboundCounter extends ChannelOutboundHandlerAdapter {

    @Autowired
    LogTerminalAccessService logTerminalAccessService;

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

        int bytesNumber = 0;
        if (ByteBuf.class.isAssignableFrom(msg.getClass())) {
            ByteBuf byteBuf = (ByteBuf) msg;
            bytesNumber = byteBuf.readableBytes();
        }
        else if (byte[].class.isAssignableFrom(msg.getClass())) {
            bytesNumber = ((byte[]) msg).length;
        }

       if (bytesNumber > 0) {
           logTerminalAccessService.saveBytesCount(ctx.channel(), bytesNumber, false);
       }
        super.write(ctx, msg, promise);
    }
}
